<template>
  <div class="UserGroupRight-container">
    <v-row class="main-wrap" no-gutters>
      <v-col class="list-wrap" :cols="3">
        <v-skeleton-loader
          v-if="loadingUserGroup"
          height="100%"
          type="list-item@20"
        ></v-skeleton-loader>
        <List
          v-else
          v-model="selectedItem"
          :items="userGroup"
          title="User Group"
        >
          <template #label="{ item }">
            {{ item.userGroupId }}- {{ item.userGroupDescription }}
          </template>
          <template #headerAppend>
            <v-icon
              class="pointer mr-3"
              color="#fff"
              small
              @click="openDeleteUserGroup(selectedItem)"
            >
              mdi-delete
            </v-icon>
            <v-icon
              class="pointer mr-2"
              color="#fff"
              small
              @click="openEditUserGroup(selectedItem)"
            >
              mdi-square-edit-outline
            </v-icon>
            <v-icon class="icon pointer" @click="openAddUserGroup">
              mdi-plus
            </v-icon>
          </template>
        </List>
      </v-col>
      <v-col class="table-wrap" :cols="9">
        <v-skeleton-loader
          v-if="loadingTable"
          height="100%"
          type="list-item@20"
        ></v-skeleton-loader>
        <Table
          v-else-if="tableItems.length > 0"
          :headers="tableHeaders"
          :items="tableItems"
          disable-sort
          hide-default-footer
          :title="tableTitle"
        >
          <template #[`header.action`]>
            <v-icon color="#fff" @click="saveRight" class="save-icon pointer">
              mdi-content-save
            </v-icon>
          </template>
          <template #item="{ item }">
            <tr class="tbody-tr">
              <td class="text-start">
                {{ item.permission }}
              </td>
              <td
                class="align-center"
                v-for="header in tableHeaders.slice(1)"
                :key="header.text"
              >
                <span
                  v-if="header.text"
                  @click="item[header.value] = !item[header.value]"
                >
                  <v-icon v-if="item[header.value]" class="icon check pointer">
                    mdi-check-bold
                  </v-icon>
                  <v-icon v-else class="icon cancel pointer" color="#EB9B31">
                    mdi-cancel
                  </v-icon>
                </span>
              </td>
            </tr>
          </template>
        </Table>
      </v-col>
    </v-row>
    <Dialog
      v-model="showDialog"
      width="480"
      :show-save="step !== 3"
      :title="dialogTitle"
      @submit="saveUserGroup"
    >
      <template>
        <AddEditUserGroup
          ref="addEditUserGroup"
          v-if="step === 1 || step === 2"
        ></AddEditUserGroup>
        <DeleteUserGroup
          @delete="deleteUserGroup"
          :item="selectedItem"
          v-else-if="step === 3"
        ></DeleteUserGroup>
      </template>
    </Dialog>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Watch } from "vue-property-decorator";
import List from "@/components/Maintenance/List/List.vue";
import Table from "@/components/Maintenance/Table/Table.vue";
import Dialog from "@/components/Maintenance/Dialog/Dialog.vue";
import AddEditUserGroup from "@/components/Maintenance/Admin/UserGroupRight/AddEditUserGroup.vue";
import DeleteUserGroup from "@/components/Maintenance/Admin/UserGroupRight/DeleteUserGroup.vue";
interface IUserGroupItem {
  id: string;
  userGroupId: string;
  userGroupDescription: string;
}

@Component({
  components: {
    List,
    Table,
    Dialog,
    AddEditUserGroup,
    DeleteUserGroup,
  },
})
export default class UserGroupRight extends Vue {
  loading = false;
  // 1.AddUserGroup 2.EditUserGroup 3.DeleteUserGroup
  step = -1;
  // dialog
  showDialog = false;
  dialogTitle = "";
  openDialog() {
    this.showDialog = true;
  }
  closeDialog() {
    this.showDialog = false;
  }
  // userGroup
  loadingUserGroup = false;
  // userGroup列表
  userGroup: IUserGroupItem[] = [];
  // 选中的userGroup
  selectedItem: IUserGroupItem | null | undefined = null;
  @Watch("selectedItem")
  onSelectedUserChange(selectedItem: IUserGroupItem | undefined) {
    if (selectedItem) {
      this.getTableItems(selectedItem.id);
    } else {
      this.tableItems = [];
    }
  }
  // 获取userGroup
  getUserGroup() {
    this.loadingUserGroup = true;
    setTimeout(() => {
      this.userGroup = [
        {
          id: "1",
          userGroupId: "CS",
          userGroupDescription: "Customer Service Team",
        },
        {
          id: "2",
          userGroupId: "CS",
          userGroupDescription: "Field Service Engineer",
        },
        {
          id: "3",
          userGroupId: "CS",
          userGroupDescription: "Project Team",
        },
        {
          id: "4",
          userGroupId: "CS",
          userGroupDescription: "Sales Team",
        },
        {
          id: "5",
          userGroupId: "CS",
          userGroupDescription: "User Group no right",
        },
      ];
      this.setDefaultSelectedUser();
      this.getTableItems((this.selectedItem as IUserGroupItem).id);
      this.loadingUserGroup = false;
    }, 800);
  }
  // 设置默认选中的userGroup
  setDefaultSelectedUser() {
    if (this.userGroup.length > 0) {
      this.selectedItem = this.userGroup[0];
    }
  }

  // Table
  loadingTable = false;
  tableHeaders = [
    {
      text: "Permission",
      value: "permission",
    },
    {
      text: "Write",
      value: "write",
      align: "center",
    },
    {
      text: "Read",
      value: "read",
      align: "center",
    },
    {
      text: "Print",
      value: "print",
      align: "center",
    },
    {
      text: "Import",
      value: "import",
      align: "center",
    },
    {
      text: "Export",
      value: "export",
      align: "center",
    },
    {
      text: "Delete",
      value: "delete",
      align: "center",
    },
    {
      text: "Change",
      value: "change",
      align: "center",
    },
    {
      value: "action",
      align: "end",
    },
  ];
  tableItems: object[] = [];
  get tableTitle() {
    if (!this.selectedItem) {
      return "";
    }
    return `${this.selectedItem.userGroupId}- ${this.selectedItem.userGroupDescription}`;
  }

  getTableItems(userGroupItemId: string) {
    this.loadingTable = true;
    setTimeout(() => {
      this.tableItems = [
        {
          permission: "Dashboard",
          write: true,
          read: true,
          print: true,
          import: true,
          export: true,
          delete: true,
          change: true,
        },
        {
          permission: "Calendar",
          write: true,
          read: true,
          print: true,
          import: true,
          export: true,
          delete: false,
          change: true,
        },
        {
          permission: "Contact",
          write: false,
          read: true,
          print: false,
          import: true,
          export: true,
          delete: false,
          change: true,
        },
      ];
      this.loadingTable = false;
    }, 800);
  }

  // action
  openAddUserGroup() {
    this.step = 1;
    this.dialogTitle = "Add User Group Detail";
    this.$nextTick(() => {
      (this.$refs.addEditUserGroup as AddEditUserGroup).resetForm();
    });
    this.openDialog();
  }
  openEditUserGroup(item: IUserGroupItem | null | undefined) {
    if (!item) {
      this.$Swal.fire({
        position: "center",
        icon: "warning",
        title: "Please select the User Group you want to edit",
        showConfirmButton: false,
        timer: 1500,
      });
      return;
    }
    this.step = 2;
    this.dialogTitle = "Edit User Group Detail";
    this.$nextTick(() => {
      const addEditUserGroupRef = this.$refs
        .addEditUserGroup as AddEditUserGroup;
      addEditUserGroupRef.resetForm();
      setTimeout(() => {
        addEditUserGroupRef.setFormData(item);
      });
    });
    this.openDialog();
  }
  openDeleteUserGroup(item: IUserGroupItem | null | undefined) {
    if (!item) {
      this.$Swal.fire({
        position: "center",
        icon: "warning",
        title: "Please select the User Group you want to delete",
        showConfirmButton: false,
        timer: 1500,
      });
      return;
    }
    this.step = 3;
    this.dialogTitle = "Delete User Group Detail";
    this.openDialog();
  }

  async saveUserGroup() {
    const result = (await (
      this.$refs.addEditUserGroup as AddEditUserGroup
    ).validateFormData()) as Record<
      "id" | "userGroupDescription" | "userGroupId",
      string
    >;
    if (result) {
      if (this.step === 1) {
        result.id = String(new Date().getTime());
        this.addUserGroup(result);
      } else if (this.step === 2) {
        this.editUserGroup(result);
      }
      this.closeDialog();
    }
  }

  addUserGroup(item: IUserGroupItem) {
    this.userGroup.push(item);
  }

  editUserGroup(item: IUserGroupItem) {
    const index = this.userGroup.findIndex(
      (userGroup) => userGroup.id === item.id
    );
    Object.assign(this.userGroup[index], item);
  }

  deleteUserGroup(id: string) {
    const index = this.userGroup.findIndex((userGroup) => userGroup.id === id);
    this.userGroup.splice(index, 1);
    this.closeDialog();
  }

  // right
  saveRight() {
    this.$Swal.fire({
      position: "center",
      icon: "success",
      title: "save successfully",
      showConfirmButton: false,
      timer: 1500,
    });
  }

  created() {
    this.getUserGroup();
  }
  mounted() {
    this.$store.commit("MaintenanceStore/switchActionIcon", "mdi-file-export");
  }
}
</script>

<style lang="scss" scoped>
@import "./UserGroupRight.scss";
</style>
